<?php
class VmFieldModel extends VmArrayModel
{
    protected $resourceId = 'SystemResource';
	protected static $instance;
    protected $parentField = 'view_id';

	public static function GetInstance()
	{
        return self::$instance ? self::$instance : self::$instance = new VmFieldModel();
	}

	public function GetByViewId($view_id)
	{
		return $this->FindBy('view_id', $view_id, null, 'sort_order');
	}

	public function InsertFields($view_id)
	{
		$count = 0;
		$model = VmViewModel::GetInstance()->GetModelById($view_id);
		foreach($model->GetFields() as $field)
		{
			$name = $field->name;
			$item = array();
			if (!$this->FieldExist($view_id, $name))
			{
				$item['view_id'] = $view_id;
				$item['name'] = $name;
				if ($field->isPrimaryKey) $item['editable'] = 0;

				if ($field->foreignKey)
				{
					$key_field = $field->foreignKey->field;
					$fkmodelname = $field->foreignKey->table;
					$ref_view = $this->GetRefview($fkmodelname);

					$fkmodel = Model::GetInstanceByName($fkmodelname);
                    $item['ref_field'] = array_key_exists('name', $fkmodel->fields) ? 'name' : $key_field;

					$item['fieldtype_id'] = $this->config->FIELDTYPE_SELECT;
					$item['drilldown_url'] = "[:url_grid:]/$ref_view#grid:filter[$key_field]=[:$name:]";
				}
				else if ($field->IsBool())
					$item['fieldtype_id'] = $this->config->FIELDTYPE_CHECKBOX;
                else if ($field->IsDatetime())
					$item['fieldtype_id'] = $this->config->FIELDTYPE_DATEPICKER;
                else if ($field->IsText())
                {
					$item['fieldtype_id'] = $this->config->FIELDTYPE_TEXTAREA;
					$item['crop_length'] = 100;
				}

				$this->Insert($item);
				$count++;
			}
		}
        MessageBase::Confirm("Grid fields inserted: $count");
	}

	public function InsertDrilldownUrl($vm_views)
	{
		$count = 0;
		foreach($vm_views as $vm_view)
		{
			$model = ModelBase::GetInstanceByName($vm_view['model_id']);
			$count += $this->InsertDrilldownUrlEach($vm_view['id'], $model);
            $fks = $model->GetForeignKeys();
			if (!empty($fks))
				VmActionModel::GetInstance()->InsertActions($model);
		}
        MessageBase::Confirm("Fields updated: $count");
	}

	protected function InsertDrilldownUrlEach($view_id, $model)
	{
		$count = 0;
		foreach($model->fields as $field)
		{
			$name = $field->name;
			$item = $this->GetByViewIdAndName($view_id, $name);
			if ($item && String::NullOrEmpty($item['drilldown_url']) && $field->foreignKey)
			{
				$key_field = $field->foreignKey->field;
				$ref_view = $this->GetRefview($field);
				$item['drilldown_url'] = "$ref_view#grid:filter[$key_field]=[:$name:]";
				$this->Update($item);
				$count++;
			}
		}
		return $count;
	}

	protected function GetRefview($fkmodelname)
	{
		return VmViewModel::GetInstance()->GetNameByModel($fkmodelname);
	}

	protected function FieldExist($view_id, $name)
	{
    	$cond = new SqlCondition();
    	$cond->AddString('view_id', $view_id);
    	$cond->AddString('name', $name);
    	return $this->Count($cond) > 0;
	}

	public function GetByViewIdAndName($view_id, $name)
	{
        return $this->FindById("$view_id::$name");
	}

    public function FindById($id, $fields = null)
    {
        $cond = new SqlCondition();
        $cond->AddString('view_id::name', $id);
        return $this->FindOne($cond);
    }

    public function Update($item)
    {
        if (isset($item['name'])) $item['name'] = trim($item['name']);
        return parent::Update($item);
    }

    public function Insert($item)
    {
        $item['name'] = trim($item['name']);
        if (!isset($item['caption']))
            $item['caption'] = String::Humanize($item['name']);
        return parent::Insert($item);
    }

    protected function LoadFields()
    {
        $this->AddField('view_id', 'varchar', false, true);
        $this->AddField('name', 'varchar', false, true);
        $this->AddField('caption');
        $this->AddField('sort_order', 'int');
        $this->AddField('ref_field');
        $this->AddField('enabled', 'bool', false, false, 1);
        $this->AddField('editable', 'bool', false, false, 1);
        $this->AddField('fieldtype_id', 'int', false, false, $this->config->FIELDTYPE_TEXTBOX);
        $this->AddField('crop_length', 'int');
        $this->AddField('drilldown_url');
        $this->AddField('width', 'int');
        $this->AddField('css');
        $this->AddField('group');

        $this->SetForeignKey('view_id', VmViewModel::GetInstance()->GetTableName(), 'id');
        $this->SetForeignKey('fieldtype_id', VmFieldtypeModel::GetInstance()->GetTableName(), 'id');
    }

    protected function GetPrimaryKeyValue(&$item)
    {
        $pk = $this->GetPrimaryKey();
        return $item[$pk] = isset($item[$pk]) ? $item[$pk] : $item['view_id'].'::'.$item['name'];
    }

    public function ToggleEditable($selected)
    {
        return $this->ToggleSelected('editable', $selected);
    }

    public function ToggleEnabled($selected)
    {
        return $this->ToggleSelected('enabled', $selected);
    }

    public function ToggleSelected($field, $selected)
    {
        foreach ($selected as $id => $on)
        {
            $this->ToggleById($field, $id);
        }
    }

    public function ToggleById($field, $id)
    {
        $value = $this->FindScalarById($id, $field);
        $item[$this->GetPrimaryKey()] = $id;
        $item[$field] = !$value;
        $this->Update($item);
    }
}
?>
